package com.example.gateway.filter;

import com.example.gateway.service.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author zhouyp
 * @program gateway
 * @description
 * @create 2020-07-26
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {

	@Autowired
	private UserRepository userRepository;

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		System.out.println("开始执行token-filter");
		final ServerHttpRequest request = exchange.getRequest();
		final ServerHttpResponse response = exchange.getResponse();
		final HttpHeaders headers = request.getHeaders();
		final String path = request.getURI().getPath();

		if (path.startsWith("/api/user") || path.startsWith("/api/code")) {
			return chain.filter(exchange);
		}
		final List<String> tokens = headers.get("example-token");
		if (tokens != null) {
			final String value = tokens.get(0);
			final String info = userRepository.infoWithToken(value);
			if (!"".equals(info)) {
				return chain.filter(exchange);
			}
		}
		response.setStatusCode(HttpStatus.UNAUTHORIZED);
		final String data = "请求拒绝，token认证失败";
		final DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
		return response.writeWith(Mono.just(wrap));
	}

	@Override
	public int getOrder() {
		return 1;
	}
}
